<?php
/**
 * The template for displaying comments
 *
 * This is the template that displays the area of the page that contains both the current comments
 * and the comment form.
 */

// 如果评论已关闭且没有评论，则退出
if ( post_password_required() || ( !have_comments() && !comments_open() ) ) {
    return;
}

require_once get_template_directory() . '/inc/theme-comments.php';
?>
<!-- 评论区 -->
<section class="bg-white rounded-xl p-6 md:p-8 shadow-md hover:shadow-lg transition-shadow duration-300">
    <div class="flex justify-between items-center mb-8">
        <h2 class="text-2xl font-bold text-neutral-900 flex items-center">
            <span class="inline-block w-1 h-6 bg-primary rounded-full mr-3"></span>
            评论区
        </h2>
        <div class="flex items-center text-sm text-neutral-500 bg-neutral-50 px-3 py-1.5 rounded-full">
            <i class="fa fa-comments-o mr-2 text-primary"></i>
            <span>共 <span class="font-medium text-primary"><?php echo get_comments_number(); ?></span> 条评论</span>
        </div>
    </div>

    <!-- 点赞收藏等功能 -->
  
    
    <?php if ( comments_open() ) : ?>
    <!-- 评论输入框 -->
    <div class="mb-10 bg-neutral-50 rounded-xl p-5 border border-neutral-100 hover:border-neutral-200 transition-all duration-300">
        <?php
        // 评论表单参数
        $commenter = wp_get_current_commenter();
        $user = wp_get_current_user();
        $user_identity = $user->exists() ? $user->display_name : '';
        $current_user_avatar = get_user_avatar_url(get_current_user_id(), 48);
        
        $comment_args = array(
            'title_reply' => '',
            'comment_notes_before' => '',
            'comment_notes_after' => '',
            'logged_in_as' => '',
            'id_form' => 'commentform',
            'id_submit' => 'submit',
            'class_form' => 'comment-form relative',
            'class_submit' => 'absolute-submit px-5 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors shadow-sm hover:shadow-md transform hover:-translate-y-0.5 transition-all',
            'name_submit' => 'submit',
            'title_reply_to' => '回复 %s',
            'cancel_reply_link' => '取消回复',
            'label_submit' => '发布评论',
            'format' => 'html5',
            'comment_field' => '
                <div class="flex items-start relative">
                    <img src="' . esc_url($current_user_avatar) . '" alt="用户头像" class="w-10 h-10 rounded-full object-cover mr-4 border-2 border-white shadow-sm">
                    <div class="flex-grow">
                        <div class="relative">
                            <textarea 
                                id="comment" 
                                name="comment" 
                                class="w-full border border-neutral-200 rounded-lg p-3 pr-28 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none transition-all placeholder-neutral-400" 
                                rows="3" 
                                placeholder="分享你的观点..."></textarea>
                            <div class="absolute top-3 right-3">
                                <button type="submit" id="submit-btn" class="px-5 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors shadow-sm hover:shadow-md transform hover:-translate-y-0.5 transition-all">
                                    <i class="fa fa-paper-plane-o mr-1"></i> 发布
                                </button>
                            </div>
                            <div class="flex items-center space-x-3 mt-2">
                                <button type="button" id="comment-image-btn" class="text-neutral-500 hover:text-primary transition-colors p-1.5 rounded-full hover:bg-neutral-100">
                                    <i class="fa fa-image"></i> 上传图片
                                </button>
                                <button type="button" id="comment-emoji-btn" class="text-neutral-500 hover:text-primary transition-colors p-1.5 rounded-full hover:bg-neutral-100">
                                    <i class="fa fa-smile-o"></i> 插入表情
                                </button>
                                <span class="text-xs text-neutral-400">支持Markdown语法</span>
                            </div>
                        </div>
                    </div>
                </div>',
            'fields' => array(
                'author' => '<input id="author" name="author" type="text" class="hidden" value="' . esc_attr($commenter['comment_author']) . '">',
                'email' => '<input id="email" name="email" type="text" class="hidden" value="' . esc_attr($commenter['comment_author_email']) . '">',
                'url' => '<input id="url" name="url" type="text" class="hidden" value="' . esc_attr($commenter['comment_author_url']) . '">',
            ),
            'submit_field' => '<div class="form-submit hidden">%1$s %2$s</div>',
        );
        
        // 如果用户未登录，显示姓名和邮箱字段
        if (!is_user_logged_in()) {
            $comment_args['fields'] = array(
                'author' => '
                <div class="flex space-x-3 mb-3">
                    <div class="w-1/2">
                        <label for="author" class="text-sm text-neutral-600 mb-1 block">昵称<span class="text-red-500">*</span></label>
                        <input id="author" name="author" type="text" class="w-full border border-neutral-200 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" value="' . esc_attr($commenter['comment_author']) . '" required>
                    </div>
                    <div class="w-1/2">
                        <label for="email" class="text-sm text-neutral-600 mb-1 block">邮箱<span class="text-red-500">*</span></label>
                        <input id="email" name="email" type="email" class="w-full border border-neutral-200 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" value="' . esc_attr($commenter['comment_author_email']) . '" required>
                    </div>
                </div>',
                'url' => '
                <div class="mb-3">
                    <label for="url" class="text-sm text-neutral-600 mb-1 block">网站</label>
                    <input id="url" name="url" type="url" class="w-full border border-neutral-200 rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" value="' . esc_attr($commenter['comment_author_url']) . '">
                </div>',
                'cookies' => '',
            );
            
            // 修改评论字段，添加提交按钮到评论框右侧
            $comment_args['comment_field'] = '
            <div class="relative">
                <textarea 
                    id="comment" 
                    name="comment" 
                    class="w-full border border-neutral-200 rounded-lg p-3 pr-28 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none transition-all placeholder-neutral-400" 
                    rows="3" 
                    placeholder="分享你的观点..."></textarea>
                <div class="absolute top-3 right-3">
                    <button type="submit" id="submit-btn" class="px-5 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors shadow-sm hover:shadow-md transform hover:-translate-y-0.5 transition-all">
                        <i class="fa fa-paper-plane-o mr-1"></i> 发布
                    </button>
                </div>
                <div class="flex items-center space-x-3 mt-2">
                    <button type="button" id="comment-image-btn" class="text-neutral-500 hover:text-primary transition-colors p-1.5 rounded-full hover:bg-neutral-100">
                        <i class="fa fa-image"></i> 上传图片
                    </button>
                    <button type="button" id="comment-emoji-btn" class="text-neutral-500 hover:text-primary transition-colors p-1.5 rounded-full hover:bg-neutral-100">
                        <i class="fa fa-smile-o"></i> 插入表情
                    </button>
                    <span class="text-xs text-neutral-400">支持Markdown语法</span>
                </div>
            </div>';
        }
        
        comment_form($comment_args);
        ?>
    </div>
    <?php endif; ?>
    
    <?php if ( have_comments() ) : ?>
    <!-- 评论排序 -->
    <div class="flex justify-between items-center mb-6">
        <div class="text-sm text-neutral-600 font-medium">
            <i class="fa fa-list-ul mr-1 text-primary"></i> 评论列表
        </div>
        <div class="relative">
            <select id="comment-sort-select" class="appearance-none bg-white border border-neutral-200 rounded-lg px-4 py-2 pr-8 text-sm text-neutral-700 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary cursor-pointer shadow-sm">
                <option value="newest">最新评论</option>
                <option value="oldest">最早评论</option>
                <option value="popular">热门评论</option>
            </select>
            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-neutral-500">
                <i class="fa fa-chevron-down text-xs"></i>
            </div>
        </div>
    </div>
    
    <!-- 评论列表 -->
    <div class="space-y-6" id="comments-container">
        <?php
        // 自定义评论回调函数
        function wanzicms_comment($comment, $args, $depth) {
            $GLOBALS['comment'] = $comment;
            $is_author = $comment->user_id === get_the_author_meta('ID');
            $likes_count = get_comment_meta($comment->comment_ID, 'comment_likes', true) ? get_comment_meta($comment->comment_ID, 'comment_likes', true) : '0';
            ?>
            <!-- 评论项 -->
            <div id="comment-<?php comment_ID(); ?>" class="bg-neutral-50 rounded-xl p-5 hover:shadow-md transition-all duration-300 border border-transparent hover:border-neutral-100 transform hover:-translate-y-0.5" data-comment-id="<?php comment_ID(); ?>" data-comment-date="<?php echo get_comment_time('U'); ?>" data-comment-likes="<?php echo $likes_count; ?>">
                <div class="flex justify-between items-start mb-3">
                    <div class="flex items-center">
                        <?php echo get_comment_avatar($comment, 48, 'w-10 h-10 rounded-full object-cover border-2 border-white shadow-sm'); ?>
                        <div class="ml-3">
                            <h4 class="font-medium text-neutral-800 flex items-center">
                                <?php echo get_comment_author(); ?>
                                <?php if ($is_author) : ?>
                                <span class="inline-block px-2 py-0.5 bg-primary/10 text-primary text-xs rounded-full ml-1">作者</span>
                                <?php endif; ?>
                                <?php if (user_can($comment->user_id, 'manage_options')) : ?>
                                <span class="inline-block px-2 py-0.5 bg-amber-100 text-amber-600 text-xs rounded-full ml-1">管理员</span>
                                <?php endif; ?>
                            </h4>
                            <div class="text-xs text-neutral-500 flex items-center">
                                <i class="fa fa-clock-o mr-1 opacity-70"></i>
                                <?php echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . '前'; ?>
                            </div>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <span class="text-xs text-neutral-400 mr-2">#<?php echo get_comment_ID(); ?></span>
                        <button class="text-neutral-400 hover:text-neutral-600 transition-colors p-1 rounded-full hover:bg-neutral-200">
                            <i class="fa fa-ellipsis-h"></i>
                        </button>
                    </div>
                </div>
                <div class="text-neutral-700 mb-4 pl-13 comment-content"><?php comment_text(); ?></div>
                <div class="flex items-center text-sm text-neutral-500 pl-13">
                    <button class="flex items-center hover:text-primary transition-colors mr-6 like-button group" data-comment-id="<?php comment_ID(); ?>">
                        <i class="fa fa-thumbs-o-up mr-1 group-hover:animate-pulse"></i>
                        <span><?php echo $likes_count; ?></span>
                    </button>
                    <button class="flex items-center hover:text-primary transition-colors comment-reply-link-wrapper group">
                        <i class="fa fa-comment-o mr-1 group-hover:rotate-12 transition-transform"></i>
                        <span class="custom-reply-link" data-comment-id="<?php comment_ID(); ?>">回复</span>
                    </button>
                </div>
                
                <?php if ($comment->comment_parent == 0) : // 只为顶级评论添加回复框 ?>
                <!-- 回复框 - 默认隐藏 -->
                <div class="mt-4 hidden comment-respond-form pl-13" id="respond-<?php comment_ID(); ?>">
                    <div class="flex items-start bg-white p-3 rounded-lg border border-neutral-100">
                        <?php 
                        $current_user_avatar = get_user_avatar_url(get_current_user_id(), 32);
                        echo '<img src="' . esc_url($current_user_avatar) . '" alt="用户头像" class="w-8 h-8 rounded-full object-cover mr-3 border-2 border-white shadow-sm">';
                        ?>
                        <div class="flex-grow">
                            <textarea 
                                class="w-full border border-neutral-200 rounded-lg p-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none transition-all placeholder-neutral-400" 
                                rows="2" 
                                placeholder="回复 @<?php echo get_comment_author(); ?>..."></textarea>
                            <div class="flex justify-end mt-2">
                                <button class="px-3 py-1.5 bg-neutral-200 text-neutral-700 rounded-lg text-xs font-medium hover:bg-neutral-300 transition-colors mr-2 cancel-reply">
                                    取消
                                </button>
                                <button class="px-3 py-1.5 bg-primary text-white rounded-lg text-xs font-medium hover:bg-primary/90 transition-colors shadow-sm submit-reply">
                                    <i class="fa fa-reply mr-1"></i> 回复
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            <?php
        }
        
        // 显示评论列表
        wp_list_comments(array(
            'style' => 'div',
            'callback' => 'wanzicms_comment',
            'avatar_size' => 48,
            'format' => 'html5',
            'short_ping' => true,
            'reply_text' => '回复',
        ));
        ?>
        
        <?php if (get_comment_pages_count() > 1 && get_option('page_comments')) : ?>
        <!-- 加载更多评论 -->
        <div class="text-center mt-8">
            <button class="px-6 py-2.5 bg-white border border-neutral-200 text-neutral-700 rounded-lg text-sm font-medium hover:bg-neutral-50 transition-colors shadow-sm hover:shadow flex items-center mx-auto load-more-comments group">
                <i class="fa fa-refresh mr-2 group-hover:rotate-180 transition-transform duration-500"></i>
                加载更多评论
            </button>
        </div>
        <?php endif; ?>
    </div>
    <?php else: ?>
    <!-- 没有评论时显示 -->
    <div class="py-10 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-neutral-100 text-neutral-400 mb-4">
            <i class="fa fa-comments-o text-2xl"></i>
        </div>
        <p class="text-neutral-500">暂无评论，来发表第一条评论吧！</p>
    </div>
    <?php endif; ?>
</section>

<style>
/* 评论内容样式 */
.comment-content p {
    margin-bottom: 0.75rem;
}
.comment-content p:last-child {
    margin-bottom: 0;
}
.comment-content a {
    color: #165DFF;
    text-decoration: none;
    border-bottom: 1px dashed #165DFF;
}
.comment-content a:hover {
    border-bottom-style: solid;
}
.comment-content blockquote {
    border-left: 3px solid #e5e7eb;
    padding-left: 1rem;
    color: #6B7280;
    font-style: italic;
    margin: 0.75rem 0;
}
.comment-content code {
    background-color: #f3f4f6;
    padding: 0.125rem 0.25rem;
    border-radius: 0.25rem;
    font-family: monospace;
    font-size: 0.875em;
}

/* 评论动画 */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

#comments-container > div {
    animation: fadeIn 0.3s ease-out;
}

/* 点赞按钮动画 */
@keyframes likeEffect {
    0% { transform: scale(1); }
    50% { transform: scale(1.2); }
    100% { transform: scale(1); }
}
.like-button.liked i {
    animation: likeEffect 0.3s ease-out;
    color: #165DFF;
}

/* 自定义滚动条 */
textarea::-webkit-scrollbar {
    width: 6px;
}
textarea::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}
textarea::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}
textarea::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
}

/* 评论区左侧留白 */
.pl-13 {
    padding-left: 3.25rem;
}

/* 上传进度条样式 */
.upload-progress-container {
    height: 20px;
    width: 100%;
    background-color: #f3f4f6;
    border-radius: 10px;
    margin: 10px 0;
    overflow: hidden;
    position: relative;
}

.upload-progress-bar {
    height: 100%;
    background-color: #165DFF;
    width: 0;
    border-radius: 10px;
    transition: width 0.3s ease;
}

.upload-progress-text {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    text-align: center;
    line-height: 20px;
    font-size: 12px;
    color: white;
    text-shadow: 0 0 2px rgba(0,0,0,0.5);
}
</style>

<script>
jQuery(document).ready(function($) {
    console.log('评论脚本已加载');
    
    // 评论排序功能
    $('#comment-sort-select').on('change', function() {
        var sortType = $(this).val();
        console.log('排序方式:', sortType);
        
        var $comments = $('#comments-container > div');
        
        // 如果评论数量少于2，不需要排序
        if ($comments.length < 2) return;
        
        // 根据排序类型对评论进行排序
        switch (sortType) {
            case 'newest':
                sortCommentsByDate($comments, true);
                break;
            case 'oldest':
                sortCommentsByDate($comments, false);
                break;
            case 'popular':
                sortCommentsByLikes($comments);
                break;
        }
    });
    
    // 按日期排序评论
    function sortCommentsByDate($comments, isNewest) {
        $comments.sort(function(a, b) {
            var dateA = parseInt($(a).data('comment-date'));
            var dateB = parseInt($(b).data('comment-date'));
            return isNewest ? (dateB - dateA) : (dateA - dateB);
        });
        
        // 重新插入排序后的评论
        $comments.detach().appendTo('#comments-container');
        
        // 添加排序完成动画效果
        animateComments();
    }
    
    // 按点赞数排序评论
    function sortCommentsByLikes($comments) {
        $comments.sort(function(a, b) {
            var likesA = parseInt($(a).data('comment-likes'));
            var likesB = parseInt($(b).data('comment-likes'));
            // 如果点赞数相同，则按最新排序
            if (likesB === likesA) {
                var dateA = parseInt($(a).data('comment-date'));
                var dateB = parseInt($(b).data('comment-date'));
                return dateB - dateA;
            }
            return likesB - likesA;
        });
        
        // 重新插入排序后的评论
        $comments.detach().appendTo('#comments-container');
        
        // 添加排序完成动画效果
        animateComments();
    }
    
    // 评论排序后的动画效果
    function animateComments() {
        $('#comments-container > div').each(function(index) {
            var $comment = $(this);
            $comment.css('opacity', 0);
            setTimeout(function() {
                $comment.animate({opacity: 1}, 300);
            }, index * 100);
        });
    }
    
    // 自定义提交按钮点击事件
    $(document).on('click', '#submit-btn', function(e) {
        e.preventDefault();
        console.log('自定义提交按钮被点击');
        var form = $(this).closest('form');
        if (form.length > 0) {
            // 验证评论内容
            if (form.find('#comment').val().trim() === '') {
                alert('请输入评论内容');
                return false;
            }
            // 触发原始提交按钮点击
            form.find('#submit').click();
        }
    });
    
    // 监听评论表单提交事件
    $('#commentform').on('submit', function(e) {
        console.log('评论表单提交事件触发');
        // 确保表单正常提交
        var form = $(this);
        if (form.find('#comment').val().trim() === '') {
            e.preventDefault();
            alert('请输入评论内容');
            return false;
        }
    });
    
    // 为提交按钮添加额外的点击事件
    $(document).on('click', '#submit', function(e) {
        console.log('提交按钮被点击');
        // 确保表单提交
        var form = $(this).closest('form');
        if (form.length > 0 && form.find('#comment').val().trim() !== '') {
            if (!e.isDefaultPrevented()) {
                console.log('尝试手动提交表单');
                form.submit();
            }
        }
    });
    
    // 添加隐藏的文件上传输入框
    $('form#commentform').append('<input type="file" id="comment-image-upload" accept="image/*" style="display:none;">');
    console.log('添加文件上传输入框完成');
    
    // 立即检查按钮是否存在
    var imageBtn = $('#comment-image-btn');
    console.log('图片按钮是否存在:', imageBtn.length > 0);
    
    if(imageBtn.length > 0) {
        // 直接绑定事件
        imageBtn.click(function(e) {
            e.preventDefault();
            console.log('图片按钮被点击');
            $('#comment-image-upload').click();
        });
        console.log('已绑定图片按钮点击事件');
    } else {
        // 如果按钮不存在，使用事件委托
        $(document).on('click', '#comment-image-btn', function(e) {
            e.preventDefault();
            console.log('图片按钮被点击(委托)');
            $('#comment-image-upload').click();
        });
        console.log('已使用事件委托绑定图片按钮点击事件');
    }
    
    // 表情按钮点击事件
    $(document).on('click', '#comment-emoji-btn', function(e) {
        e.preventDefault();
        console.log('表情按钮被点击');
        
        // 检查表情面板是否已存在
        var emojiPanel = $('#emoji-panel');
        if (emojiPanel.length > 0) {
            // 如果已存在，切换显示/隐藏
            emojiPanel.toggle();
            return;
        }
        
        // 创建表情面板
        var emojis = ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', 
                      '😋', '😎', '😍', '😘', '🥰', '😗', '😙', '😚', '🙂', '🤗', 
                      '🤩', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😣', '😥', 
                      '😮', '🤐', '😯', '😪', '😫', '🥱', '😴', '😌', '😛', '😜', 
                      '😝', '🤤', '😒', '😓', '😔', '😕', '🙃', '🤑', '😲', '☹️', 
                      '🙁', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', 
                      '😩', '🤯', '😬', '😰', '😱', '🥵', '🥶', '😳', '🤪', '😵', 
                      '🥴', '😠', '😡', '🤬', '😷', '🤒', '🤕', '🤢', '🤮', '🤧'];
        
        var panel = $('<div id="emoji-panel" class="bg-white border border-neutral-200 rounded-lg p-2 shadow-lg" style="position: absolute; z-index: 100; max-width: 300px;"></div>');
        var grid = $('<div class="grid grid-cols-8 gap-1"></div>');
        
        // 添加表情
        $.each(emojis, function(i, emoji) {
            var emojiBtn = $('<button class="w-8 h-8 text-lg hover:bg-neutral-100 rounded" type="button">' + emoji + '</button>');
            emojiBtn.on('click', function() {
                // 将表情插入到评论框
                var $textarea = $('#comment');
                var caretPos = $textarea[0].selectionStart;
                var textAreaTxt = $textarea.val();
                $textarea.val(textAreaTxt.substring(0, caretPos) + emoji + textAreaTxt.substring(caretPos));
                
                // 设置光标位置
                var newCaretPos = caretPos + emoji.length;
                $textarea[0].setSelectionRange(newCaretPos, newCaretPos);
                $textarea.focus();
                
                // 隐藏表情面板
                panel.hide();
            });
            grid.append(emojiBtn);
        });
        
        panel.append(grid);
        
        // 添加关闭按钮
        var closeBtn = $('<button class="absolute top-1 right-1 text-neutral-400 hover:text-neutral-600" type="button"><i class="fa fa-times"></i></button>');
        closeBtn.on('click', function() {
            panel.hide();
        });
        panel.append(closeBtn);
        
        // 添加到页面
        var btnPosition = $(this).offset();
        panel.css({
            top: btnPosition.top + $(this).outerHeight() + 5,
            left: btnPosition.left
        });
        $('body').append(panel);
        
        // 点击其他区域关闭表情面板
        $(document).on('click', function(e) {
            if (!$(e.target).closest('#emoji-panel, #comment-emoji-btn').length) {
                $('#emoji-panel').hide();
            }
        });
    });
    
    // 文件选择后的处理
    $('#comment-image-upload').on('change', function(e) {
        console.log('文件已选择');
        var file = this.files[0];
        if (!file) return;
        
        // 检查文件类型
        if (!file.type.match('image.*')) {
            alert('请选择图片文件！');
            return;
        }
        
        // 检查文件大小（限制为2MB）
        if (file.size > 2 * 1024 * 1024) {
            alert('图片大小不能超过2MB！');
            return;
        }
        
        console.log('开始上传图片');
        
        // 检查wp_comment_params是否存在
        if (typeof wp_comment_params === 'undefined') {
            console.error('wp_comment_params未定义，请检查functions.php中的脚本加载');
            alert('上传功能初始化失败，请刷新页面重试');
            return;
        }
        
        var formData = new FormData();
        formData.append('action', 'upload_comment_image');
        formData.append('image', file);
        formData.append('security', wp_comment_params.upload_nonce);
        
        // 显示上传进度
        var $textarea = $(this).closest('form').find('textarea');
        var $progressContainer = $('<div class="upload-progress-container"><div class="upload-progress-bar"></div><div class="upload-progress-text">0%</div></div>');
        $textarea.after($progressContainer);
        
        $.ajax({
            url: wp_comment_params.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function() {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round((evt.loaded / evt.total) * 100);
                        $('.upload-progress-bar').css('width', percentComplete + '%');
                        $('.upload-progress-text').text(percentComplete + '%');
                    }
                }, false);
                return xhr;
            },
            success: function(response) {
                console.log('上传成功', response);
                $progressContainer.remove();
                if (response.success) {
                    // 在评论内容中插入图片标记
                    var imageTag = '\n![' + file.name + '](' + response.data.url + ')\n';
                    var currentContent = $textarea.val();
                    $textarea.val(currentContent + imageTag);
                } else {
                    alert(response.data.message || '上传失败，请重试！');
                }
            },
            error: function(xhr, status, error) {
                console.error('上传失败', status, error);
                $progressContainer.remove();
                alert('上传失败，请重试！');
            }
        });
    });
    
    // 自定义回复链接处理
    $(document).on('click', '.custom-reply-link', function(e) {
        e.preventDefault();
        console.log('回复按钮被点击');
        
        var commentId = $(this).data('comment-id');
        console.log('评论ID:', commentId);
        
        // 先隐藏所有回复框
        $('.comment-respond-form').addClass('hidden');
        
        // 显示当前评论的回复框
        var replyForm = $('#respond-' + commentId);
        if (replyForm.length > 0) {
            replyForm.removeClass('hidden');
            replyForm.find('textarea').focus();
        } else {
            console.log('未找到回复框:', '#respond-' + commentId);
        }
        
        // 阻止默认的WordPress回复行为
        return false;
    });
    
    // 取消回复按钮点击事件
    $(document).on('click', '.cancel-reply', function(e) {
        e.preventDefault();
        $(this).closest('.comment-respond-form').addClass('hidden');
    });
    
    // 提交回复按钮点击事件
    $(document).on('click', '.submit-reply', function(e) {
        e.preventDefault();
        console.log('提交回复按钮被点击');
        
        var $replyForm = $(this).closest('.comment-respond-form');
        var commentId = $replyForm.attr('id').replace('respond-', '');
        var content = $replyForm.find('textarea').val().trim();
        
        if (content === '') {
            alert('请输入回复内容');
            return;
        }
        
        // 检查是否登录
        if (typeof wp_comment_params === 'undefined' || !wp_comment_params.is_user_logged_in) {
            alert('请先登录后再回复');
            return;
        }
        
        // 显示加载状态
        var $submitBtn = $(this);
        var originalText = $submitBtn.html();
        $submitBtn.html('<i class="fa fa-circle-o-notch fa-spin mr-1"></i> 提交中...');
        $submitBtn.prop('disabled', true);
        
        // 发送AJAX请求提交回复
        $.ajax({
            url: wp_comment_params.ajax_url,
            type: 'POST',
            data: {
                action: 'submit_comment_reply',
                comment_id: commentId,
                content: content,
                security: wp_comment_params.reply_nonce
            },
            success: function(response) {
                console.log('回复提交结果:', response);
                
                if (response.success) {
                    // 隐藏回复框
                    $replyForm.addClass('hidden');
                    
                    // 清空输入框
                    $replyForm.find('textarea').val('');
                    
                    // 显示成功消息
                    alert('回复已提交，等待审核');
                    
                    // 如果不需要审核，可以直接刷新页面显示新回复
                    if (response.data && response.data.no_moderation) {
                        location.reload();
                    }
                } else {
                    alert(response.data.message || '回复提交失败，请重试');
                }
            },
            error: function() {
                alert('网络错误，请重试');
            },
            complete: function() {
                // 恢复按钮状态
                $submitBtn.html(originalText);
                $submitBtn.prop('disabled', false);
            }
        });
    });
    
    // 点赞功能
    $(document).on('click', '.like-button', function() {
        var $this = $(this);
        var $count = $this.find('span');
        var commentId = $this.data('comment-id');
        var currentLikes = parseInt($count.text());
        
        // 检查是否已经点赞过
        if ($this.hasClass('liked')) {
            // 发送AJAX请求取消点赞
            if (typeof wp_comment_params !== 'undefined') {
                $.ajax({
                    url: wp_comment_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'unlike_comment',
                        comment_id: commentId,
                        security: wp_comment_params.like_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // 取消点赞成功，更新UI
                            $this.removeClass('liked');
                            $count.text(response.data.likes);
                            // 更新数据属性，用于排序
                            $this.closest('[data-comment-id]').attr('data-comment-likes', response.data.likes);
                        } else {
                            alert(response.data.message || '取消点赞失败');
                        }
                    },
                    error: function() {
                        alert('网络错误，请重试');
                    }
                });
            }
        } else {
            // 发送AJAX请求添加点赞
            if (typeof wp_comment_params !== 'undefined') {
                $.ajax({
                    url: wp_comment_params.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'like_comment',
                        comment_id: commentId,
                        security: wp_comment_params.like_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // 点赞成功，更新UI
                            $this.addClass('liked');
                            $count.text(response.data.likes);
                            // 更新数据属性，用于排序
                            $this.closest('[data-comment-id]').attr('data-comment-likes', response.data.likes);
                        } else {
                            alert(response.data.message || '点赞失败');
                        }
                    },
                    error: function() {
                        alert('网络错误，请重试');
                    }
                });
            }
        }
    });
    
    // 评论框自动调整高度
    $('textarea').on('input', function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });
    
    // 加载更多评论
    $('.load-more-comments').on('click', function() {
        var $button = $(this);
        $button.html('<i class="fa fa-circle-o-notch fa-spin mr-2"></i> 加载中...');
        
        // 这里可以添加AJAX加载更多评论的代码
        // 示例：延迟2秒模拟加载
        setTimeout(function() {
            $button.html('<i class="fa fa-refresh mr-2"></i> 加载更多评论');
            // 如果没有更多评论可加载，可以禁用按钮
            // $button.attr('disabled', true).addClass('opacity-50 cursor-not-allowed').html('没有更多评论了');
        }, 2000);
    });
});
</script>
